package pers.burgess.fsm.client.core;

import java.io.IOException;

import pers.burgess.fsm.client.gui.BashListener;
import pers.burgess.fsm.client.gui.ClientGUI;
import pers.burgess.fsm.model.Message;

public class Handler {
	
	private Client client = null;
	private ClientGUI clientGUI = null;
	
	private String serverAddress = null;
	private int port = -1;
	
	public Handler (Client client, ClientGUI clientGUI) {
		this.client = client;
		this.clientGUI = clientGUI;
		initializeClient();
	}
	
	private void initializeClient() {
		this.clientGUI.append("initialize client", true);
		this.client.setClientListener(new ClientStatusChangedListener() {

			public void onChanged(ClientStatus clientStatus) {
				switch (clientStatus) {
					case READY:
						clear();
						clientGUI.append("please input server address", false);
					break;
					case DO_CONNECT:
						clientGUI.append("connect to " + serverAddress + ":" + port, true);
						break;
					case CONNECTING:
						Message initMessage = new Message("path", "", Message.CLIENT_MSG);
						try {
							initMessage = client.readMessage();
						} catch (Exception e) {
							clientGUI.append("path", false);
						} finally {
							clientGUI.append(initMessage.getHeader(), false);
						}
						break;
					case DISCONNECT:
						clientGUI.append("disconnect", true);
					break;
					case CONNECT_FAILED:
						clientGUI.append("connect failed", true);
						break;
				}
			}
			
		});

		this.clientGUI.append("please input server address", false);
		
		this.clientGUI.setBashListener(new BashListener() {

			public void newCommand(String command) {
				
				if (client.getClientStatus() == ClientStatus.READY) {
					
					if (serverAddress == null) {
						serverAddress = command;
						clientGUI.append("please input server port", false);
					} else {
						port = Integer.valueOf(command);
						client.connect(serverAddress, port);
					}

				} else if (client.getClientStatus() == ClientStatus.CONNECTING) {
					
					Message outerMessage = new Message(null, command, Message.CLIENT_MSG);
					try {
						Message innerMessage = client.requestServer(outerMessage, !command.toUpperCase().trim().equals("EXIT"));
						if (innerMessage != null) {
							clientGUI.append("\n" + innerMessage.getMessage(), true);
							clientGUI.append(innerMessage.getHeader(), false);
						}
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					if (command.toUpperCase().trim().equals("EXIT")) {
						client.disconnect();
					}
					
				} else {
					// clientGUI.append("", true);
				}
			}
			
		});
		
	}

	
	private void clear () {
		this.serverAddress = null;
		this.port = -1;
	}
}
